package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomException;
import com.itheima.dao.CategoryDao;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

    /*
    * 根据 id 删除分类
    * 删除之前需要进行判断
    * 判断"菜品分类" or "套餐分类"
    * */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category>
            implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetMealService setMealService;

    @Override
    public void remove(Long id) {
        //添加查询条件 根据分类id进行查询菜品数据
            //创建条件构造器
        LambdaQueryWrapper<Dish> queryWrapper1 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Setmeal> queryWrapper2 = new LambdaQueryWrapper<>();
            //添加条件
        queryWrapper1.eq(Dish::getCategoryId,id);
        queryWrapper2.eq(Setmeal::getCategoryId,id);
            //调用方法查询
        int count1 = dishService.count(queryWrapper1);
        int count2 = setMealService.count(queryWrapper2);
            //如果已经关联,则抛出一个业务异常
        if (count1 > 0){
            throw new CustomException("已关联菜品,删除失败");
        }else if (count2 > 0){
            throw new CustomException("已关联套餐,删除失败");
        }else {
            //都无关联,正常删除分类
            super.removeById(id);
        }
    }
}
